package ua.epam.muzalevskiy.traction.dao;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ResourceBundle;
import org.apache.log4j.Logger;

/**
 * This is realization of
 * <code> ConnectionFactory </code> with C3P0 Connection Pool.
 *
 * @author Muzalevskiy Vitaliy
 */
public class ConnectionFactoryC3P0 implements ConnectionFactory { 
    private static final Logger LOGGER  = 
            Logger.getLogger(ConnectionFactoryC3P0.class);  
    /**This value need to connect to DataBase.*/
    private static final String JDBC_URL;
    /**Login that we need to connect to concrete DataBase Server.*/
    private static final String LOGIN;  
    /**Password that we need to connect to concrete DataBase Server.*/
    private static final String PASSWORD;  
    /**The name of concrete JDBC Driver that we need to create 
     * connection to DataBase Server.*/
    private static final String DRIVER_CLASS;
    private final ComboPooledDataSource dataSource;

    static {
        final ResourceBundle config = ResourceBundle
                .getBundle("ua.epam.muzalevskiy.traction.dao.dbconnection");
        DRIVER_CLASS = config.getString("db.driver.class");
        JDBC_URL = config.getString("db.url");
        LOGIN = config.getString("db.login");
        PASSWORD = config.getString("db.password");
    }

    /**
     *
     * @throws SQLException
     */
    public ConnectionFactoryC3P0() throws SQLException {
        try {
            dataSource = new ComboPooledDataSource();

            dataSource.setDriverClass(DRIVER_CLASS);
            dataSource.setJdbcUrl(JDBC_URL);
            dataSource.setUser(LOGIN);
            dataSource.setPassword(PASSWORD);

            dataSource.setMaxStatements(180);
            dataSource.setMaxStatementsPerConnection(10);
            dataSource.setMinPoolSize(1);
            dataSource.setAcquireIncrement(1);
            dataSource.setMaxPoolSize(20);
        } catch (PropertyVetoException e) {
            throw new RuntimeException("Exception during configuration c3p0", e);
        }
    }

    @Override
    public Connection newConnection() throws SQLException {
        return dataSource.getConnection();
    }

    @Override
    public void close() throws SQLException {
        dataSource.close();
    }
}
